<?php

class TreeBuildController extends Controller
{   
    public $defaultAction = 'admin';
    public $layout = '//layouts/package';


    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
//            array('deny',  // deny all users
//                'users'=>array('*'),
//            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
        $package = $this->loadModel($id);
        $config = simplexml_load_file($xmlPath.$package->file.'.xml');
        
        //$config = new SimpleXMLElement;        
        //$config->
        //$config = new DOMDocument;
        //$config->load($xmlPath.$package->file.'.xml');
        //var_dump($config->getElementsByTagName('package'));
       // $cur_package = new SimpleXMLElement($package_xml);
        //echo $package_xml->asXML();
        $this->render('view',array(
            'data'=>$this->loadModel($id),
            'config'=>$config
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
            $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
            $model=new Package;
            if(isset($_POST['name']))
            {
                $model->name=$_POST['name'];
                $model->cate_id = 1;
                $model->file = Package::convertVietNgu($_POST['name']);            
                $model->desc = $_POST['description'];
                $model->create_by = Yii::app()->user->id;

                if($model->save()) {
                    //$root = Category::model()->findByPk($model->cate_id);
                    $string = '<?xml version="1.0" encoding="UTF-8"?><package>';
                    $package = $_POST['Product'];
                    $packageAmount = $_POST['Amount'];
                    
                    for ($i = 0; $i < sizeof($package); $i++){
                        $criteria = new CDbCriteria;
        //              $criteria->compare('name', $name);
                        $criteria->condition = "name LIKE :name";
                        $criteria->params = array(":name"=>"%$package[$i]%");
                        $product = Product::model()->find($criteria);
                        if ($product != null){
                            $string .= '<product>';
                            $string .= '<id>'.$product->id.'</id>';
                            $string .= '<name>'.$product->name.'</name>';
                            $string .= '<amount>'.$packageAmount[$i].'</amount>';
                            $string .= '</product>';
                        }else{
                            $pack = Package::model()->find($criteria);
                            if ($pack != null){
                                $string .= '<pack>';
                                $string .= '<id>'.$pack->id.'</id>';
                                $string .= '<name>'.$pack->name.'</name>';
                                $string .= '<amount>'.$packageAmount[$i].'</amount>';
                                $string .= '</pack>';
                            }else{
                                $string .= '<pack>';
                                $string .= '<id>0</id>';
                                $string .= '<name>'.$package[$i].'</name>';
                                $string .= '<amount>'.$packageAmount[$i].'</amount>';
                                $string .= '</pack>';
                            }
                        }
                    }
                    $string .= '</package>';
                    $package = new SimpleXMLElement($string);
                    $package->asXML($xmlPath.$model->file.'.xml');

                    $this->redirect(array('buildTree/view','id'=>$model->id));
              }
            }
            $dataProvider = new CActiveDataProvider('Product',
                        array(
                            'criteria' => array(
                        'order' => 'RAND() '
                    )
                        )
                        );
                $dataProvider->pagination->pageSize = 5;
            $this->render('create',array(
                'dataProvider' => $dataProvider
        ));
    }

    public function actionSearch(){
        $packages = array();
        if (isset($_GET['case'])){
            $name = $_GET['case'];
            $criteria = new CDbCriteria;
//            $criteria->compare('name', $name);
            $criteria->condition = "name LIKE :name ";
            $criteria->params = array(":name"=>"%$name%");
            $packages = Package::model()->findAll($criteria);
            
            //search  product
            $criteria->condition = "name LIKE :name OR description LIKE :name";
            $criteria->params = array(":name"=>"%$name%");
            $products = Product::model()->findAll($criteria);
        }
        $this->render('result', array(
            'packages' => $packages,
            'products' => $products
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Package');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        
        
        $model=new Package('search');
        
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Package']))
            $model->attributes=$_GET['Package'];

        $this->render('admin',array(
            'model'=>$model,
            'cate_root'=>$this->getSubCate(0)
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Package::model()->findByPk((int)$id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='package-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
        public function getSubCate($cate_id=null) {
//            if($cate_id==null) {
//                return false;
//            }
//            else {
                $subCate = Yii::app()->db->createCommand()
                              ->select(array('id','name'))
                              ->from('category')
                              ->where('parent_id = '.$cate_id)
                              ->queryAll();
                    ;             
                if(null==$subCate)                    return FALSE;
                else                    return $subCate;
            
        }
        
        public function actionSearchAuto(){
        $res = array();
        if (isset($_GET['term'])){
            $name = $_GET['term'];
            $criteria = new CDbCriteria;
//            $criteria->compare('name', $name);
            $criteria->condition = "name LIKE :name";
            $criteria->params = array(":name"=>"%$name%");
            $products = Product::model()->findAll($criteria);
            $packages = Package::model()->findAll($criteria);
            foreach ($products as $product)
                $res[] = $product->name;
            foreach ($packages as $package)
                $res[] = $package->name;
        }
        echo CJSON::encode($res);
        Yii::app()->end();
    }
    
        public function actionTest(){
            $package = Package::model()->findByPk(12);
            var_dump($package->readPackage());
        }
        

	
}